/**
 * Created by wry on 2015/5/14.
 */
var toolUtil = require('../../common/utils/toolUtil');
var mysqlUtil = require('../../common/utils/mysqlUtil');
var Banner = mongoose.model('community_banner');
var BannerBind = mongoose.model('community_banner_bind');
var async = require('async');
var moment = require('moment');
var Question = mongoose.model('question');
var Activity = mongoose.model('activity_neighbour');
var Topic = mongoose.model('system_specialTopics');
var Notice = mongoose.model('community_bulletins');
var freshNews = mongoose.model('system_freshNews');
var lottery = mongoose.model('backoffice_lotteries');
var SystemBanner = mongoose.model('system_BannerDefinitions');


exports.addCommunityBanner = function (input, callback) {

    var communityIds = input.community;
    if (typeof communityIds == 'string') {
        communityIds = [communityIds]
    }

    delete  input.community;

    input.openType = Number(input.openType);

    switch (input.openType) {
        case 1:                 //问题详情
            input.tag = freshName.question.tagName;
            input.bgColor = freshName.question.bgColor;
            break;
        case 2:                 //公告详情
            input.tag = freshName.notice.tagName;
            input.bgColor = freshName.notice.bgColor;
            break;
        case 3:                 //抽奖
            input.tag = freshName.lottery.tagName;
            input.bgColor = freshName.lottery.bgColor;
            break;
        case 4:                 //专题
            input.tag = freshName.topic.tagName;
            input.bgColor = freshName.topic.bgColor;
            break;
        case 6:                 //活动详情
            input.tag = freshName.activity.tagName;
            input.bgColor = freshName.activity.bgColor;
            break;
    }

    var temp = new Banner(input);
    temp.save(function (err, result) {
        communityIds.forEach(function (communityId) {
            var temp = new BannerBind();
            temp.bannerId = result._id;
            temp.community = communityId;
            temp.type = input.type;
            temp.displayOrder = moment().format('YYYYMMDDHHmmss');
            temp.save();
        });
        callback();
    });

    if (input.type == 2) {
        var temp1 = new freshNews();
        temp1.displayOrder = moment().format('YYYYMMDDHHmmss');
        if (input.openType == 1) {
            temp1.openType = 3;
            temp1.tag = input.tag;
            temp1.newsId = input.contentId;
            temp1.createdBy = input.contentCreatedBy;
            temp1.title = input.message;
            temp1.bgColor = input.bgColor;
            temp1.community = communityIds;
            temp1.url = input.contentUrl;
            temp1.save();
        } else if (input.openType == 2) {
            temp1.openType = 1;
            temp1.tag = input.tag;
            temp1.newsId = input.contentId;
            temp1.createdBy = input.contentCreatedBy;
            temp1.title = input.message;
            temp1.bgColor = input.bgColor;
            temp1.community = communityIds;
            temp1.url = input.contentUrl;
            temp1.save();
        } else if (input.openType == 6) {
            temp1.openType = 7;
            temp1.tag = input.tag;
            temp1.newsId = input.contentId;
            temp1.createdBy = input.contentCreatedBy;
            temp1.title = input.message;
            temp1.bgColor = input.bgColor;
            temp1.community = communityIds;
            temp1.url = input.contentUrl;
            temp1.save();
        }
    } else if (input.type == 1) {
        if (input.openType == 2 || input.openType == 3 || input.openType == 4) {

            var banner = {
                displayOrder: 1,
                activityId: input.contentId,
                title: input.title,
                desc: input.contentUrl,
                backgroundImageURL: input.imageURL
            };
            async.each(communityIds, function (communityId, c1) {
                SystemBanner.findOne({community: communityId}, function (err, banners) {
                    if (banners != null) {
                        SystemBanner.update({community: communityId}, {$push: {'banner': banner}}, c1)
                    } else {
                        var temp = new SystemBanner();
                        temp.community = communityId;
                        temp.banner = [banner];
                        temp.save(c1);
                    }
                })
            })
        }
    }
};

exports.deleteCommunityBanner = function (bannerId, callback) {
    async.series([
        function (callbackInner) {
            BannerBind.find({bannerId: bannerId}, function (err, result) {
                if (result != null) {
                    async.each(result, function (bind, c1) {
                        exports.deleteBannerBindService(bind._id, c1);
                    }, function () {
                        callbackInner();
                    })
                } else {
                    callbackInner()
                }
            })
        },
        function (callbackInner) {
            Banner.remove({_id: bannerId}, callbackInner);
        }
    ], callback)
};

exports.updateCommunityBanner = function (input, callback) {

    Banner.update({_id: input.bannerId}, input, callback)
};


exports.getAllContentListByCommunityIdService = function (input, callback) {

    var pageSize = 20;

    var index = (input.page - 1) * pageSize;

    async.series([
        function (callbackInner) {
            Question.find({community: input.community})
                .skip(index).limit(pageSize).sort('-dateCreated')
                .populate('community', 'communityName')
                .populate('createdBy', 'nickName')
                .exec(function (err, result) {
                    callbackInner(null, result)
                })
        },
        function (callbackInner) {
            Activity.find({community: input.community})
                .skip(index).limit(pageSize).sort('-dateCreated')
                .populate('community', 'communityName')
                .populate('createdBy', 'nickName')
                .exec(function (err, result) {
                    callbackInner(null, result)
                })
        },
        function (callbackInner) {
            Topic.find({community: {$all: input.community}})
                .skip(index).limit(pageSize).sort('-dateCreated')
                .populate('community', 'communityName')
                .exec(function (err, result) {
                    if (result != null && result.length > 0) {
                        result.forEach(function (topic) {
                            topic._doc['url'] = TopicsHost + '/' + topic._id + '.html'
                        });
                    }
                    callbackInner(null, result);
                });
        },
        function (callbackInner) {
            Notice.find({community: {$all: input.community}})
                .skip(index).limit(pageSize).sort('-dateCreated')
                .populate('community', 'communityName')
                .exec(function (err, result) {
                    if (result != null && result.length > 0) {
                        result.forEach(function (notice) {
                            notice._doc['url'] = NoticeHost + '/' + notice._id + '.html'
                        });
                    }
                    callbackInner(null, result);
                });
        },
        function (callbackInner) {
            if (input.community != null && input.community.length > 0) {
                var sql = 'SELECT COUNT(lottery_id),lottery_id FROM lottery_activity_community_map where 1=1';
                input.community.forEach(function (id) {
                    sql += ' or community_id = "' + id + '"'
                });
                sql += ' group by lottery_id HAVING COUNT(lottery_id)>';
                sql += input.community.length - 1;

                logger.info(sql);
                mysqlUtil.query(sql, function (err, result) {
                    if (result != null && result.length > 0) {
                        var ids = '';
                        result.forEach(function (lotteryId) {
                            ids += lotteryId.lottery_id + ','
                        });

                        ids = ids.substr(0, ids.length - 1);

                        var sqlStr = 'SELECT * FROM lottery_activity WHERE id IN (' + ids + ')';
                        logger.info(sqlStr);
                        mysqlUtil.query(sqlStr, function (err, result) {
                            if (result != null) {
                                result.forEach(function (lottery) {
                                    lottery.url = lotteryUrl
                                });
                            }
                            callbackInner(null, result);
                        });
                    } else {
                        callbackInner();
                    }
                })
            } else {
                callbackInner()
            }
        },
        function (callbackInner) {
            lottery.find({community: input.community, url: {$ne: null}}, function (err, result) {
                //if (result != null && result.length > 0) {
                //    result[0]._doc['url'] = 'http://' + AppHost + '/a/total/cj.html'
                //}
                callbackInner(null, result)
            })
        }
    ], callback);
};


exports.getBannerListService = function (page, type, callback) {
    var index = (Number(page) - 1) * 20;
    async.series([

        function (callbackInner) {
            BannerBind.count({type: Number(type)}, function (err, count) {
                callbackInner(err, Math.ceil(count / 20));
            });
        },
        function (callbackInner) {
            BannerBind.find({type: Number(type)}).skip(index).limit(20).sort('-dateCreated').populate('bannerId').populate('community', 'communityName').exec(function (err, result) {
                if (result != null)
                    callbackInner(null, result);
            });
        }
    ],callback);
};

exports.getBannerDetailService = function (bannerId, callback) {
    var openType;
    async.series([
        function (callbackInner) {
            Banner.findOne({_id: bannerId}, function (err, result) {
                openType = result.openType;
                result._doc.imageURL = fastDfsHostIp + result._doc.imageURL;
                callbackInner(err, result);
            })
        },
        function (callbackInner) {
            Banner.findOne({_id: bannerId}, function (err, result) {
                if (openType == 1) {
                    Question.findOne({_id: result.contentId}).populate('createdBy', 'nickName images')
                        .populate('community', '_id communityName')
                        .exec(function (err, result) {
                            result._doc.community = [result._doc.community];
                            result._doc['tagName'] = '话题';
                            callbackInner(err, result);
                        })
                } else if (openType == 2) {
                    Notice.findOne({_id: result.contentId}, function (err, notice) {
                        notice._doc['url'] = NoticeHost + '/' + notice._id + '.html';
                        notice._doc['tagName'] = '公告';
                        callbackInner(null, notice);
                    }).populate('community', '_id communityName')
                } else if (openType == 4) {
                    Topic.findOne({_id: result.contentId}, function (err, topic) {
                        topic._doc['url'] = TopicsHost + '/' + topic._id + '.html';
                        topic._doc['tagName'] = '专题';
                        callbackInner(null, topic);
                    }).populate('community', '_id communityName')
                } else if (openType == 6) {
                    Activity.findOne({_id: result.contentId}).populate('createdBy', 'nickName images')
                        .populate('community', '_id communityName')
                        .exec(function (err, result) {
                            result._doc.community = [result._doc.community];
                            result._doc['tagName'] = '邻里活动';
                            callbackInner(err, result);
                        });
                } else {
                    callbackInner()
                }
            })
        },
        function (callbackInner) {
            BannerBind.find({bannerId: bannerId}).populate('community', 'communityName').exec(function (err, result) {
                var bindIds;
                if (result != null) {
                    result.forEach(function (bind) {
                        bindIds += bind.community._id;
                    })
                }
                callbackInner(null, data);
                var data = {
                    bindIds: bindIds,
                    bindList: result
                };
            })
        }
    ], callback);
};

exports.deleteBannerBindService = function (id, callback) {
    BannerBind.findOne({_id: id}, function (err, bind) {
        async.series([
            function (callbackInner) {
                if (bind.type == 1) {
                    SystemBanner.update({community: bind.community}, {
                        $pull: {
                            banner: {
                                activityId: bind.bannerId.contentId
                            }
                        }
                    }, callbackInner)
                } else {
                    callbackInner();
                }
            },
            function (callbackInner) {
                BannerBind.remove({_id: id}, callbackInner);
            }
        ], callback);
    }).populate('bannerId', 'contentId');
};

exports.bindCommunityBannerService = function (input, callback) {
    async.each(input.community, function (communityId, callbackInner) {
        var temp = new BannerBind();
        temp.bannerId = input.bannerId;
        temp.community = communityId;
        temp.type = input.type;
        temp.save(callbackInner);
    }, function (err) {
        callback();
    })
};

exports.getCommunityBannerListService = function (communityId, type, callback) {
    BannerBind.find({
        community: communityId,
        type: Number(type)
    }).populate('bannerId', 'imageURL contentId openType message').sort('-displayOrder')
        .exec(function (err, result) {
            if (result != null) {
                result.forEach(function (bind) {
                    if (bind.bannerId._doc.imageURL != null)
                        bind.bannerId._doc.imageURL = fastDfsHostIp + bind.bannerId._doc.imageURL;
                })
            }
            callback(err, result);
        })
};

exports.setBindBannerOrderService = function (input, callback) {
    BannerBind.update({_id: input.bindId}, {displayOrder: input.displayOrder}, callback);
};

exports.setdBannerBinOrderService = function (input, callback) {
    var a = input.length;
    logger.debug(input);
    logger.debug(a);
    async.eachSeries(input, function (bindId, callbackInner) {
        BannerBind.update({_id: bindId}, {displayOrder: a}, function (err, result) {
            logger.debug(a);
            a--;
            callbackInner(err, result);
        })
    }, function (err) {
        callback(err, null);
    })
};

exports.confirmPushGroupTopicService = function (input, callback) {

    var banner = {};

    switch (input.openType) {
        case "1":                 //问题详情
            banner.tag = freshName.question.tagName;
            banner.bgColor = freshName.question.bgColor;
            break;
        case 6:                 //活动详情
            banner.tag = freshName.activity.tagName;
            banner.bgColor = freshName.activity.bgColor;
            break;
    };

    banner.title =  input.title;
    banner.message =  input.message;
    banner.openType = input.openType
    banner.type= input.type;

    var tpicList = input.topicList;

    async.eachSeries(tpicList, function (tpic, callbackInner) {


        banner.community = tpic.community;
        banner.contentId = tpic.contentId;
        banner.contentCreatedBy = tpic.createdBy;

        var temp = new Banner(banner);
        temp.save(function (err, result) {
            //communityIds.forEach(function (communityId) {
                var bind = new BannerBind();
                bind.bannerId = result._id;
                bind.community = banner.community;
                bind.type = input.type;
                bind.displayOrder = moment().format('YYYYMMDDHHmmss');
                bind.save();
            //});
            callbackInner();
        });


    }, function (err) {
        callback(err, null);
    });


    //var temp = new Banner(input);
    //temp.save(function (err, result) {
    //    communityIds.forEach(function (communityId) {
    //        var temp = new BannerBind();
    //        temp.bannerId = result._id;
    //        temp.community = communityId;
    //        temp.type = input.type;
    //        temp.displayOrder = moment().format('YYYYMMDDHHmmss');
    //        temp.save();
    //    });
    //    callback();
    //});

};

exports.PushGroupBannerService = function (input, callback){

    var banner = {};

    switch (input.openType) {
        case "1":                 //问题详情
            banner.tag = freshName.question.tagName;
            banner.bgColor = freshName.question.bgColor;
            break;
        case 6:                 //活动详情
            banner.tag = freshName.activity.tagName;
            banner.bgColor = freshName.activity.bgColor;
            break;
    };

    //banner.title =  input.title;
    //banner.message =  input.message;
    banner.openType = input.openType;
    banner.type= input.type;
    banner.imageURL = input.imageURLs;

    var tpicList = input.topicList;
    async.eachSeries(tpicList, function (tpic, callbackInner) {

        banner.community = tpic.community;
        banner.contentId = tpic.contentId;
        banner.contentCreatedBy = tpic.createdBy;

        var temp = new Banner(banner);
        temp.save(function (err, result) {
            //communityIds.forEach(function (communityId) {
            var bind = new BannerBind();
            bind.bannerId = result._id;
            bind.community = banner.community;
            bind.type = input.type;
            bind.displayOrder = moment().format('YYYYMMDDHHmmss');
            bind.save();
            //});
            callbackInner();
        });


    }, function (err) {
        callback(err, null);
    });




};

exports.deleteBannerByFiltersService = function (input, callback) {

    async.eachSeries(input.banners, function (banner, callbackInner) {

        async.series([
            function (callbackInner) {
                //logger.debug(banner.bannerId._id);
                BannerBind.find({bannerId: banner.bannerId._id}, function (err, result) {
                    if (result != null) {
                        async.each(result, function (bind, c1) {
                            exports.deleteBannerBindService(bind._id, c1);
                        }, function () {
                            callbackInner();
                        })
                    } else {
                        callbackInner()
                    }
                })
            },
            function (callbackInner) {
                Banner.remove({_id: banner.bannerId._id}, callbackInner);
            }
        ], callbackInner)

    }, function (err) {
        callback(err, null);
    });
};